package top.cyuw.subjectsystem.security;

import org.springframework.security.core.authority.SimpleGrantedAuthority;
import top.cyuw.subjectsystem.constant.JwtConstants;
import top.cyuw.subjectsystem.exception.ServiceException;
import top.cyuw.subjectsystem.util.JwtTokenUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.web.authentication.www.BasicAuthenticationFilter;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Collections;

public class JwtAuthenticationFilter extends BasicAuthenticationFilter {

    public JwtAuthenticationFilter(AuthenticationManager authenticationManager) {
        super(authenticationManager);
    }

    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain chain) throws IOException, ServletException {
        String accessToken = request.getHeader(JwtConstants.HEADER_ACCESS_TOKEN);

        if (StringUtils.isEmpty(accessToken)) {
            chain.doFilter(request, response);
            return;
        }

        if (JwtTokenUtils.isExpiration(accessToken)) {
            throw new ServiceException(401, "令牌已过期");
        }

        Integer userId = JwtTokenUtils.getUserId(accessToken);
        if (userId == null || userId <= 0) {
            throw new ServiceException(400, "请求错误");
        }

        String userRole = JwtTokenUtils.getUserRole(accessToken);
        if (StringUtils.isEmpty(userRole)) {
            throw new ServiceException(400, "请求错误");
        }

        UsernamePasswordAuthenticationToken authentication = new UsernamePasswordAuthenticationToken(null, userId, Collections.singleton(new SimpleGrantedAuthority(userRole)));
        SecurityContextHolder.getContext().setAuthentication(authentication);

        super.doFilterInternal(request, response, chain);
    }

}

